package com.lelouch.wetlandcommon.tools;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MapServerFromXmlTool {

    public static List<String> findMapServerUrls(String mapServer, String ip, String port) {
        SAXReader saxReader = new SAXReader();
        Document document = null;
        ArrayList<String> mapserver = new ArrayList<String>();
        if (StringUtils.isBlank(mapServer)) {
            return new ArrayList<String>();
        } else {
            try {
                document = saxReader.read(downloadXML("http://" + ip + ":" + port + "/arcgis/rest/services/" + mapServer + "?f=sitemap"));
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            // 获取根元素
            Element root = document.getRootElement();
            // 获取特定名称的子元素
            List<Element> childList2 = root.elements("url");
            for (Element element : childList2) {
                mapserver.add(element.elementText("loc"));
            }
            return mapserver;
        }

    }

    public static InputStream downloadXML(final String urlStr) {
        InputStream inStream = null;
        URL url = null;
        try {
            url = new URL(urlStr);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        conn.setConnectTimeout(5 * 1000);
        try {
            conn.setRequestMethod("GET");
            conn.connect();
        } catch (Exception e) {
        }
        try {
            inStream = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inStream;
    }
}
